from mastodon import Mastodon as M
from optparse import OptionParser
import datetime
import json

# https://stackoverflow.com/questions/56554159/typeerror-object-of-type-datetime-is-not-json-serializable-with-serialize-fu
class DateTimeEncoder(json.JSONEncoder):
    def default(self, z):
        if isinstance(z, datetime.datetime):
            return (str(z))
        else:
            return super().default(z)

import sys
import re

parser = OptionParser()
parser.add_option("-a", "--api-token", dest="apitoken",
                  help="use this APITOKEN", metavar="APITOKEN")
parser.add_option("-s", "--server", dest="server",
                  help="use this INSTANCE", metavar="INSTANCE")

(options, args) = parser.parse_args()

if len(args) < 1:
    print("required: toot", file=sys.stderr)
    sys.exit(-1)

toot = args[0]

def connect_mastodon():
    m = M(
        api_base_url=options.server,
        access_token=options.apitoken,
        ratelimit_pacefactor=2.0,
    )
    return m

def roottoot(tootid):
    ancestors = m.status_context(id=tootid).get('ancestors')
    if len(ancestors) == 0:
        return tootid
    else:
#        print(ancestors[0].get('id'))
        return roottoot(ancestors[0].get('id'))

from collections import defaultdict

import lxml
from lxml import html
from lxml.html.clean import clean_html
from lxml import etree

def tree(tootid, indent):
    toot = m.status(id=tootid)
    tooturi = toot.get('uri')
    ind = ' '*indent
    print('%s%s %s' % (ind, '->', tooturi))
    print(ind + "   " + clean_html(html.fromstring(toot['content'])).text_content()+"\n")
    themap = defaultdict(set)
    descendants = m.status_context(id=tootid).get('descendants')
    for node in descendants:
        if node.get('in_reply_to_id') == int(tootid):
            themap[tootid].add(node.get('id'))
            themap.update(tree(node.get('id'), indent+2))
    return themap

m = connect_mastodon()
myid = m.me().id

st = m.status(id=toot)
root = roottoot(toot)
tree(root, indent=0)

    

